package com.example.chatroom.common.utils;

import cn.hutool.crypto.digest.DigestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Slf4j
@Component
public class DigesterUtils {
    @Autowired
    private UUIDUtil uuidUtil;
    /**
     * md5加密
     * @param str 待加密字符串
     * @param salt 盐值
     * @return
     */
    public String encrypt(String str,String salt){
        log.info("MD5 encrypt str:{}",str);
        if(!StringUtils.hasLength(str)){
            log.error("encrypt str:{}",str);
            return null;
        }
        //原文+盐值 进行加密
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(str);
        stringBuilder.append(salt);
        //密文
        String secret=DigestUtil.md5Hex(stringBuilder.toString());
        log.info("MD5 encrypt 加密后的值:{}",secret);
        return secret;
    }


    /**
     * 校验md5加密的结果
     * @param plaintext 原文 待校验原文
     * @param ciphertext 密文 从数据库获取的密文
     * @param salt 盐值 从数据库获取
     * @return
     */
    public boolean verify(String plaintext,String ciphertext,String salt){
        log.info("MD5 verify plaintext:{} ciphertext:{}",plaintext,ciphertext);
        if(!StringUtils.hasLength(plaintext)||!StringUtils.hasLength(ciphertext)){
            log.error("MD5 verify 参数异常 plaintext:{} ciphertext:{}",plaintext,ciphertext);
            return false;
        }
        //将原文和盐值拼接后进行md5加密
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(plaintext);
        stringBuilder.append(salt);
        String encrypt = encrypt(plaintext,salt);
        //比较字符串是否相等
        if(!encrypt.equalsIgnoreCase(ciphertext)){
            return false;
        }
        return true;
    }
}
